<?php

namespace app\model;

use think\Model;

class UserModel extends Model
{
    //默认主键为id，如果你没有使用id作为主键名，需要在模型中设置属性
//    protected $pk = 'csc_id';
//    // 设置当前模型对应的完整数据表名称
    protected $table = 'csc_user';

    // 设置当前模型的数据库连接
    protected $connection = 'mysql';
//    use SoftDelete;
//    protected $deleteTime = 'csc_isdel';
//    protected $defaultSoftDelete = 0;

//    public function deleteUser($id)
//    {
//        var_dump('zz');exit();
//        $result = $this->where('csc_id',$id)->find();
//        return $result;
//    }

    public function userExpendOne()
    {
        return $this->hasOne(UserExpendOne::class,'csc_user_id','csc_id');
    }

    public function userCoupon()
    {
        return $this->hasMany(UserCoupon::class,'csc_user_id','csc_id');
    }

    public function userDataList($info)
    {
        $result = UserModel::hasWhere('userExpendOne',['buy_city'=>'乐山市'])->where($info)->field('csc_user,csc_user.csc_id,csc_phone,buy_city,csc_company,csc_shen,csc_buy_tag,csc_reg_time')->limit(3)->select();
//        $user = UserModel::has('userCoupon','>',3)->where('csc_user.csc_shen',$info['csc_shen'])->limit(3)->select();
//        var_dump($user);exit();
//        $result = UserModel::hasWhere('userExpendOne',function($query) use($info){
//            $query->where('buy_city','like','%'.$info['buy_city'].'%');
//        })->field('csc_user,csc_user.csc_id,csc_phone,buy_city')->select();
        return $result;
    }
    public function getUserById($id)
    {
//        $result = UserModel::name('csc_user')->where('csc_id', $id)->find();
        //var_dump($result->userExpendOne->buy_city);exit();//一对一关联
//        $coupons = $result->userCoupon()->where('csc_use',0)->select();//一对多关联
//        $result = UserModel::withCount(['userCoupon'=>function ($query,&$alias){
//            $query->where('csc_use',0);
//            $alias = 'coupon_num';
//        }])->where('csc_id',$id)->select();
        $result = UserModel::withSum('userCoupon','csc_price')->where('csc_id', $id)->find();
//        var_dump($result);exit();

//        var_dump($coupons);exit();
        return $result;
    }

    public function addUser($data)
    {
        $result = UserModel::name('csc_user')->insertGetId($data);
        return $result;
    }

    public function updateUser($data)
    {
        $result = UserModel::name('csc_user')->where('csc_id', $data['csc_id'])->update($data);
        return $result;
    }

    public static function onAfterDelete($user)
    {
        $user->userExpendOne()->delete();
    }

    public function deleteUser($id)
    {
        $user = UserModel::with('userExpendOne')->where('csc_id',$id)->find();
//        $re = $user->userExpendOne()->delete();
        $result = $user->delete();
        return $result;
    }
}